<template>
  <div class="form">
    <el-form :model="todolist" label-width="auto" inline>
      <el-form-item label="请设置标签大小：">
      </el-form-item>
      <el-form-item label="宽" width="30px">
        <el-input v-model="todolist.widthPx" />
      </el-form-item>
      <el-form-item label="高">
        <el-input v-model="todolist.heightPx" />
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="todolist.checked1" label="锁定比例" size="large" />
      </el-form-item>
    </el-form>
  </div>
  <div>
    需要打印的信息推拽：
    <!-- <draggable v-model="todolist.names" @end="onDragEnd">
      <template >
        <div class="list-item">
          {{ 11111 }}
        </div>
      </template>
</draggable> -->
    <transition-group name="drag" class="list" tag="ul" style="display: flex">
      <div v-for="(item, index) in todolist.names" :key="item.label" draggable
        :class="['list-item', { 'is-dragover': index === dragOverIndex }]" @dragstart="dragStart(item, index)"
        @mousedown="dragStart(item, index)" @dragover.prevent="dragOver(index)" @dragend="dragEnd()">
        {{ item.label }}
      </div>
    </transition-group>
  </div>
  <div class="one">
    <div id="drop" ref="dropArea"
      :style="{ width: parseInt(todolist.widthPx * 4.68) + 'px', height: parseInt(todolist.heightPx * 4.68) + 'px', border: '3px solid black', backgroundColor: 'pink', position: 'relative', overflow: 'hidden' }"
      @dragover.prevent="allowDrop" @drop="dropItem">
    </div>
    <!-- <img src='http://yitaoweb.sc.kuaidi600.com/expressMoban.png' />
    <img src='http://yitaoweb.sc.kuaidi600.com/xiao.png' />
    <img src='http://yitaoweb.sc.kuaidi600.com/expressMoban.png' /> -->
  </div>
  <button @click="sets">保存配置</button>

</template>

<script setup>
import { ref, onBeforeMount, onBeforeUpdate, watch, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { sysPrintTemplateSetGetSysPrintTemplateSetDetail, sysPrintTemplateSetUpdate } from '@/api/index'
// import { draggable } from 'vuedraggable'
const route = useRoute()

onBeforeMount(() => {
  getDetile(route.query.ID)
})
onMounted(() => {

})
const IDs = ref('')
watch(IDs, (e, a) => {
  getDetile(route.query.ID)
  dropItem()
})

onBeforeUpdate(() => {
  IDs.value = route.query.ID
})
const getDetile = (id) => {
  sysPrintTemplateSetGetSysPrintTemplateSetDetail({ id: id }).then(res => {
    const { data: { data } } = res
    orderId.value = data.orderId
    todolist.value.widthPx = data.wide
    todolist.value.heightPx = data.high
    todolist.value.names = data.labelJson ? JSON.parse(data.labelJson) : todolist.value.names
  })
}
const orderId = ref(null)
const todolist = ref(
  {
    checked1: false,
    widthPx: 100,
    heightPx: 100,
    names: [
      { label: '条形码', top: '', left: '', isOr: false, name: 'waybillCode', width: '65', height: '20', id: '1', barCodeLabel: true },
      // { label: 'SKU信息', top: '', left: '', isOr: false, name: 'list2', width: '65', height: '', id: '2' },
      { label: '库位号', top: '', left: '', isOr: false, name: 'list3', width: '65', height: '', id: '3' }
    ]
  }
)
const dragStartIndex = ref('')
const dragStartData = ref('')
const dragOverIndex = ref('')
// 拖动列表
const dragStart = (item, index) => {
  dragStartIndex.value = index
  dragStartData.value = item
}
// 鼠标指针进入放置区域才触发
const dragOver = (index) => {
  dragOverIndex.value = index
  console.log(dragStartData.value)
}
const dragEnd = () => {
  const copyTodolist = [...todolist.value.names]
  // 删除老的节点
  copyTodolist.splice(dragStartIndex.value, 1)
  // 在列表中目标位置增加新的节点
  copyTodolist.splice(dragOverIndex.value, 0, dragStartData.value)
  todolist.value.names = [...copyTodolist]
  dragOverIndex.value = ''
}

const dropArea = ref()
// const allowDrop = () => {
//   console.log('dragOverIndex.value')
// }
const offsetX = ref('')
const offsetY = ref('')
// 创建页面模板
const dropItem = (event) => {
  console.log('event')
  console.log(event)
  if (event) {
    // 位置
    const rect = dropArea.value.getBoundingClientRect()
    console.log('rect')
    console.log(todolist.value)
    offsetX.value = event.clientX - rect.left
    offsetY.value = event.clientY - rect.top
    todolist.value.names.forEach(element => {
      // if (element.label === dragStartData.value.label) {
      element.top = offsetY.value + 'px'
      element.left = offsetX.value + 'px'
      // 删除同名元素
      const existingElement = dropArea.value.querySelector(`.${dragStartData.value.name}`)
      console.log('name')
      console.log(existingElement)
      if (existingElement) {
        dropArea.value.removeChild(existingElement)
      }
      // 创建新的元素
      // newElement.setAttribute('img', 'myValue'); 添加属性
      const newElement = document.createElement('span')
      newElement.style.width = (dragStartData.value.width * 4.68) + 'px'
      newElement.style.height = (dragStartData.value.height * 4.68) + 'px'
      newElement.style.backgroundColor = 'red'
      newElement.style.display = 'inline-block'
      newElement.className = dragStartData.value.name
      newElement.innerHTML = dragStartData.value.label
      newElement.style.position = 'absolute'
      newElement.style.top = offsetY.value + 'px'
      newElement.style.left = offsetX.value + 'px'
      // newElement.addEventListener('dragstart', dragStart())
      // 添加删除
      newElement.addEventListener('contextmenu', function (event) {
        event.preventDefault()
        removeDom(newElement)
      })
      dropArea.value.appendChild(newElement)
      console.log(dropArea.value)
      // }
    })
  } else {
    todolist.value.names.forEach(element => {
      if (element.isOr) {
        const existingElement = dropArea.value.querySelector(`.${element.name}`)
        console.log('names')
        console.log(existingElement)
        if (existingElement) return
        // 创建新的元素
        // newElement.setAttribute('img', 'myValue'); 添加属性
        const newElement = document.createElement('span')
        newElement.style.width = (element.width * 4.68) + 'px'
        newElement.style.height = (element.height * 4.68) + 'px'
        newElement.style.backgroundColor = 'red'
        newElement.style.display = 'inline-block'
        newElement.className = element.name
        newElement.innerHTML = element.label
        newElement.style.position = 'absolute'
        newElement.style.top = (element.top * 4.68) + 'px'
        newElement.style.left = (element.left * 4.68) + 'px'
        // newElement.addEventListener('contextmenu', removeDom(newElement))
        newElement.addEventListener('contextmenu', function (event) {
          event.preventDefault()
          removeDom(newElement)
        })
        dropArea.value.appendChild(newElement)
        console.log(dropArea.value)
      }
    })
  }
}
// 右击删除
const removeDom = (newElement) => {
  console.log(newElement)
  console.log('name')
  console.log(newElement)
  todolist.value.names.forEach(e => {
    if (newElement.className === e.name) {
      dropArea.value.removeChild(newElement)
      e.isOr = false
    }
  })
}
// 创建模板
const heads = ref('<?xml version="1.0" encoding="UTF-8"?>')
const canshuArr = ref('')
const templateCreate = ref(`
<page
        xmlns="http://cloudprint.cainiao.com/print"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://cloudprint.cainiao.com/print http://cloudprint-docs-resource.oss-cn-shanghai.aliyuncs.com/lpml_schema.xsd"
        xmlns:editor="http://cloudprint.cainiao.com/schema/editor"
        width="${todolist.value.widthPx}" height="${todolist.value.heightPx}"   splitable="true">
 `)
const nextTemplate = ref('')
const TemplateContent = ref('')
const sets = () => {
  TemplateContent.value = ''
  canshuArr.value = ''
  const a = document.querySelector('#drop')
  for (let index = 0; index < a.children.length; index++) {
    const leftPx = a.children[index].style.left.replace(/px/g, '')
    const topPx = a.children[index].style.top.replace(/px/g, '')
    const widthCode = a.children[index].style.width.replace(/px/g, '')
    const heightCode = a.children[index].style.height.replace(/px/g, '')
    canshuArr.value += `var ${a.children[index].className} = _data.${a.children[index].className}\n`
    todolist.value.names.forEach(e => {
      if (a.children[index].className === e.name) {
        if (e.barCodeLabel) {
          TemplateContent.value += `  <layout width="${todolist.value.widthPx}" height="${Number(heightCode) / 4.68}" left="${Number(leftPx) / 4.68}" top="${Number(topPx) / 4.68}" style="zIndex:999999">
    <barcode  width="${Number(widthCode) / 4.68}" type="code128" ratioMode="ignoreRatio" style="hideText:false;rotation:0;">
      <![CDATA[<%=${a.children[index].className}%>]]>
    </barcode>
  </layout>\n`
        } else {
          TemplateContent.value += `<layout width="${todolist.value.widthPx}" orientation="vertical" left="${Number(leftPx) / 4.68}" top="${Number(topPx) / 4.68}"  style="zIndex:3;">
              <text
                  style="fontFamily:SimHei;fontSize:12;">
                  <![CDATA[<%=${a.children[index].className}%>]]>
              </text>
  </layout>\n`
        }
        e.top = Number(topPx) / 4.68
        e.left = Number(leftPx) / 4.68
        e.isOr = true
      }
    })
    TemplateContent.value = TemplateContent.value.replace(/<\/page>/g, '')
    TemplateContent.value += '</page>'
  }
  nextTemplate.value = heads.value + templateCreate.value + `<%
${canshuArr.value}
%>\n` + TemplateContent.value
  console.log(nextTemplate.value)
  sysPrintTemplateSetUpdate({
    orderId: orderId.value,
    wide: todolist.value.widthPx,
    tableLeft: 0,
    tableTop: 0,
    high: todolist.value.heightPx,
    labelJson: JSON.stringify(todolist.value.names),
    isLock: todolist.value.checked1 ? 1 : 0,
    printTemplate: nextTemplate.value
  }).then(res => {
    ElMessage.success('保存成功')
    getDetile(route.query.ID)
  })
}
</script>

<style lang='less' scoped>
.draggable {
  position: absolute;
  width: 100px;
  height: 100px;
  cursor: pointer;
  background-color: #3498db;
  color: white;
  padding: 20px;
  border-radius: 10px;
  user-select: none;
  transition: all 0.2s;
}

.form {
  display: flex;
  align-items: center;
}

.list {
  list-style: none;

  .drag-move {
    transition: transform 0.3s;
  }

  .list-item {
    position: relative;
    cursor: move;
    width: 100px;
    background: #EA6E59;
    border-radius: 4px;
    color: #FFF;
    margin: 10px 20px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }
}

.list-item .is-dragover::before {
  content: "";
  position: absolute;
  bottom: -8px;
  left: 0;
  width: 100%;
  height: 4px;
  background-color: #0c6bc9;
}

.list-item.is-dragover::after {
  content: "";
  position: absolute;
  bottom: -12px;
  left: -6px;
  border: 3px solid #0c6bc9;
  border-radius: 50%;
  width: 6px;
  height: 6px;
  background-color: #fff;
}

.listssss {
  width: 100px;
  background: #EA6E59;
  border-radius: 4px;
  color: #FFF;
  margin: 10px 20px;
  height: 50px;
  line-height: 50px;
  text-align: center;

}

.one {
  display: flex;
  align-items: flex-start
}
</style>
